package com.cloudm.technician.ui.modules.cloudm_box.upload_pic_token

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.cloudm.technician.R
import com.cloudm.technician.data.model.DeviceInfo
import com.cloudm.technician.data.model.ImageInfo
import com.cloudm.technician.data.model.UploadTokenInfo
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.extensions.string
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BasePermissionsFragment
import com.cloudm.technician.ui.base.PicBottomDialogFragment
import com.cloudm.technician.ui.modules.cloudm_box.pic_preview.PicPreviewActivity
import com.cloudm.technician.ui.modules.cloudm_box.transfer.TransferActivity
import com.cloudm.technician.ui.modules.cloudm_box.upload_pic.UploadPicAdapter
import com.cloudm.technician.ui.widget.SpaceItemDecoration
import kotlinx.android.synthetic.main.fragment_upload_pic_token.*
import java.io.File

/**
 * 作者: wesley
 * 时间: 2017/12/23
 * 描述: ui
 */
class UploadTokenPicFragment : BasePermissionsFragment<UploadPicTokenPresenter>(),
        UploadPicTokenContract.View, UploadPicAdapter.OnItemClickListener,
        PicBottomDialogFragment.OnItemClickListener {

    private var info: DeviceInfo? = null
    private var channelId: String? = null
    private var position: Int = -1

    override val resource: Int
        get() = R.layout.fragment_upload_pic_token

    private val adapter: UploadPicAdapter by lazy {
        UploadPicAdapter(mContext, 1)
    }

    companion object {
        private const val TAG = "UploadTokenPicFragment"
        private const val REQUEST_CODE_PREVIEW_PIC = 1
        fun newInstance(info: DeviceInfo?, channelId: String?) = UploadTokenPicFragment().apply {
            arguments = Bundle().apply {
                putParcelable("info", info)
                putString("channelId", channelId)
            }
        }
    }

    override fun initInject() {
        DaggerUploadTokenPicComponent.builder().appComponent(
                appComponent).uploadTokenPicPresenterModule(
                UploadTokenPicPresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {
        info = bundle.getParcelable("info")
        channelId = bundle.getString("channelId", null)
    }

    override fun initVariables() {
        adapter.listener = this
    }

    override fun initViews(view: View) {
        recyclerView.layoutManager = GridLayoutManager(mContext, 3)
        recyclerView.addItemDecoration(SpaceItemDecoration(
                mContext.resources.getDimensionPixelSize(R.dimen.common_margin_16dp)))
        recyclerView.adapter = adapter

        presenter?.buildImageInfo()
    }

    override fun initListener() {

    }

    override fun buildImageInfoSuccess(list: ArrayList<ImageInfo>) {
        adapter.addAllItems(list)
    }

    override fun takePic() {
        requestPermissionsForCamera()
    }

    override fun takeFromGalley() {
        requestPermissionFromGalley()
    }

    override fun onItemClick(info: ImageInfo, position: Int) {
        presenter?.onItemClick(info, position)
    }


    override fun showBottomDialogFragment(position: Int) {
        this.position = position
        val fragment = PicBottomDialogFragment.newInstance()
        fragment.listener = this
        fragment.show(childFragmentManager, TAG)
    }

    override fun showLoadingMsg(position: Int, url: String) {
        mContext.toast("本地图片")
        openPicPreviewActivity(position, url)
    }

    override fun openPicPreviewActivity(position: Int, url: String) {
        this.position = position
        val intent = Intent(mContext, PicPreviewActivity::class.java).apply {
            putExtras(Bundle().apply {
                putString("url", url)
            })
        }
        startActivityForResult(intent, REQUEST_CODE_PREVIEW_PIC)
    }

    override fun showTokenInfoEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
    }

    override fun updateUiByFlag(flag: Int, position: Int) {
        adapter.updateUi(position, flag, "")
    }

    override fun loadTokenInfoSuccess(info: UploadTokenInfo, file: File, position: Int) {
        presenter?.uploadFile(info, file, position)
    }

    override fun showErrorMsg(errorMsg: String) {
        mContext.toast(errorMsg)
    }

    override fun picUploadFailure() {
        mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
    }

    override fun showUploadPercent(position: Int, percent: Double) {
        adapter.updateUi(position, 1, percent)
    }

    override fun picUploadSuccess(url: String, position: Int) {
        adapter.updateUi(position, 2, url)
    }

    override fun getOrderNumber(): String? = etOrderNumbers.string()

    override fun showOrderNumberEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_order_numbers))
    }

    override fun showUnknowError() {
        mContext.toast(mContext.resources.getString(R.string.unknow_error))
    }

    override fun showPicEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_upload_a_pic))
    }

    override fun openTransferActivity(orderNumber: String, url: String) {
        val intent = Intent(mContext, TransferActivity::class.java).apply {
            putExtras(Bundle().apply {
                putParcelable("info", info)
                putString("channelId", channelId)
                putString("orderNumber", orderNumber)
                putString("url", url)
            })
        }
        mContext.openActivity(intent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            REQUEST_CODE_PREVIEW_PIC -> {
                adapter.updateUi(position, 0, "")
            }
        }
    }

    override fun takePictureSuccess(path: String) {
        super.takePictureSuccess(path)
        adapter.updateUi(position, 1, path)
        compressImage(path, position)
    }

    override fun takeFromGalleySuccess(path: String) {
        super.takeFromGalleySuccess(path)
        adapter.updateUi(position, 1, path)
        compressImage(path, position)
    }

    private fun compressImage(path: String, position: Int) {
        compressImageByLuban(path, onSuccess = { info ->
            presenter?.getUploadToken(info, position)
        }, onFailure = {
            mContext.toast(mContext.resources.getString(R.string.pic_upload_failure))
            adapter.updateUi(position, 0, path)
        })
    }

    fun onNext() {
        presenter?.onNextClick(getOrderNumber(), adapter.list)
    }
}